package com.jiutong.meipenggang.ui.activitys;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.Toast;

import com.chechezhi.ui.guide.FragmentTabAdapter;
import com.chechezhi.ui.guide.SinglePage;
import com.gyf.barlibrary.ImmersionBar;
import com.jiutong.meipenggang.R;
import com.jiutong.meipenggang.base.AppManager;
import com.jiutong.meipenggang.base.BaseActivity;
import com.jiutong.meipenggang.common.Constants;
import com.jiutong.meipenggang.ui.fragments.EntryFragment;
import com.jiutong.meipenggang.utils.NetworkUtil;
import com.jiutong.meipenggang.utils.PermissionsResultListener;
import com.jiutong.meipenggang.utils.SpConfig;

import java.util.ArrayList;
import java.util.List;

/**
 * com.best.bestedu.activity
 * create for 引导页  引导客户进入APP
 * Created by liuqi on 2016/7/25.
 */
public class GuideActivity extends AppCompatActivity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        List guideContent = this.buildGuideContent();
        if(guideContent != null) {
            FrameLayout container = new FrameLayout(this);
            ViewPager pager = new ViewPager(this);
            pager.setId(this.getPagerId());
            container.addView(pager, new ViewGroup.LayoutParams(-1, -1));
            setContentView(container);

            AppManager.getAppManager().addActivity(this);

            //激活沉浸式状态栏  第三方库ImmersionBar
            ImmersionBar.with(this).fitsSystemWindows(false).statusBarDarkFont(true,0.2f).init();


            FragmentTabAdapter adapter = new FragmentTabAdapter(this, guideContent);
            pager.setAdapter(adapter);
//            GuideView guideView = new GuideView(this, guideContent, this.drawDot(), this.dotDefault(), this.dotSelected());
//            pager.setOnPageChangeListener(guideView);
//            container.addView(guideView, new FrameLayout.LayoutParams(-1, -1));
        }

        //权限申请
        requestPermissions();

    }

    /**
     * 权限申请
     */
    private void requestPermissions() {
        performRequestPermissions(new String[]{Manifest.permission.ACCESS_NETWORK_STATE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.CALL_PHONE,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.ACCESS_NETWORK_STATE,
                Manifest.permission.CAMERA,
                Manifest.permission.INTERNET}, 1, new PermissionsResultListener() {
            @Override
            public void onPermissionGranted() {
                if (!NetworkUtil.isNetworkConnected(GuideActivity.this)) {
                    Toast.makeText(GuideActivity.this,"没有网络访问，请检查您的网络连接",Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onPermissionDenied() {
                Toast.makeText(GuideActivity.this,getResources().getString(R.string.permission_get_accounts_hint),Toast.LENGTH_SHORT).show();
            }
        });
    }



    public List<SinglePage> buildGuideContent() {
        List<SinglePage> guideContent = new ArrayList<>();

        SinglePage page01 = new SinglePage();
        page01.mBackground = getResources().getDrawable(R.mipmap.guide_page1);
        guideContent.add(page01);

        SinglePage page02 = new SinglePage();
        page02.mBackground = getResources().getDrawable(R.mipmap.guide_page2);
        guideContent.add(page02);

        SinglePage page03 = new SinglePage();
        page03.mBackground = getResources().getDrawable(R.mipmap.guide_page3);
        guideContent.add(page03);

        SinglePage page04 = new SinglePage();
        page04.mCustomFragment = new EntryFragment();
        guideContent.add(page04);

//        SinglePage page04 = new SinglePage();
//        page03.mCustomFragment = new EntryFragment();
//        guideContent.add(page04);

        return guideContent;
    }

    public boolean drawDot() {
        return true;
    }

    public Bitmap dotDefault() {
        return BitmapFactory.decodeResource(getResources(),R.mipmap.gray_noselected_point);
    }

    public Bitmap dotSelected() {
        return BitmapFactory.decodeResource(getResources(),R.mipmap.gray_noselected_point);
    }

    public int getPagerId() {
        return R.id.guide_container;
    }


    public void entryApp(){
        SpConfig.getInstance().putBool(Constants.IS_FIRST_USE_BOOLEAN, false);
        Intent intent = new Intent(this,MainActivity.class);
        startActivity(intent);
        finish();
    }

    private PermissionsResultListener mListener;

    private int mRequestCode;

    /**
     * 其他 Activity 继承 BaseActivity 调用 performRequestPermissions 方法
     * <p>
     * //     * @param desc        首次申请权限被拒绝后再次申请给用户的描述提示
     *
     * @param permissions 要申请的权限数组
     * @param requestCode 申请标记值
     * @param listener    实现的接口
     */
    protected void performRequestPermissions(String[] permissions, int requestCode, PermissionsResultListener listener) {
        if (permissions == null || permissions.length == 0) {
            return;
        }
        mRequestCode = requestCode;
        mListener = listener;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            // 检查是否声明了权限
            if (checkEachSelfPermission(permissions)) {
                requestEachPermissions(permissions, requestCode);
            } else {// 已经申请权限
                if (mListener != null) {
                    mListener.onPermissionGranted();
                }
            }
        } else {
            if (mListener != null) {
                mListener.onPermissionGranted();
            }
        }
    }

    /**
     * 申请权限前判断是否需要声明
     *
     * @param permissions
     * @param requestCode
     */
    private void requestEachPermissions(String[] permissions, int requestCode) {
        //申请权限前判断是否需要声明的dialog，默认不需要
//        if (shouldShowRequestPermissionRationale(permissions)) {// 需要再次声明
//            showRationaleDialog(permissions, requestCode);
//        } else {
        ActivityCompat.requestPermissions(GuideActivity.this, permissions, requestCode);
//        }
    }

    /**
     * 弹出声明的 Dialog
     *
     * @param permissions
     * @param requestCode
     */
    private void showRationaleDialog(final String[] permissions, final int requestCode) {
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("")
                .setMessage("请记得添加权限哦！")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        ActivityCompat.requestPermissions(GuideActivity.this, permissions, requestCode);
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                    }
                })
                .setCancelable(false)
                .show();
    }

    /**
     * 再次申请权限时，是否需要声明
     *
     * @param permissions
     * @return
     */
    private boolean shouldShowRequestPermissionRationale(String[] permissions) {
        for (String permission : permissions) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 检察每个权限是否申请
     *
     * @param permissions
     * @return true 需要申请权限,false 已申请权限
     */
    private boolean checkEachSelfPermission(String[] permissions) {
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                return true;
            }
        }
        return false;
    }

    /**
     * 申请权限结果的回调
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == mRequestCode) {
            if (checkEachPermissionsGranted(grantResults)) {
                if (mListener != null) {
                    mListener.onPermissionGranted();
                }
            } else {// 用户拒绝申请权限
                if (mListener != null) {
                    mListener.onPermissionDenied();
                }
            }
        }
    }

    /**
     * 检查回调结果
     *
     * @param grantResults
     * @return
     */
    private boolean checkEachPermissionsGranted(int[] grantResults) {
        for (int result : grantResults) {
            if (result != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

}
